package com.cloud.check.api.service.impl;

import com.cloud.check.api.bean.RecCheckCriteriaBean;
import com.cloud.check.api.bean.HumanDetail;
import com.cloud.check.api.bean.RecCheckForm;
import com.cloud.check.api.bean.RecCheckSearchBean;
import com.cloud.check.api.entity.CheckTaskNumSeq;
import com.cloud.check.api.entity.RecCheck;
import com.cloud.check.api.entity.RecCheckItem;
import com.cloud.check.api.mapper.ChecKTaskNumSeqMapper;
import com.cloud.check.api.mapper.RecCheckItemMapper;
import com.cloud.check.api.mapper.RecCheckMapper;
import com.cloud.check.api.service.RecCheckService;
import com.cloud.check.common.context.HumanSession;
import com.cloud.check.common.result.SelectItem;
import com.cloud.check.common.utils.DateHelper;
import com.cloud.check.common.utils.RedisKeyHelper;
import com.cloud.check.common.utils.SessionHelper;
import com.cloud.check.interfaces.FeignClientSystem;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class RecCheckServiceImpl implements RecCheckService {
    @Autowired
    private RecCheckMapper recCheckMapper;

    @Autowired
    private RecCheckItemMapper recCheckItemMapper;

    @Autowired
    private FeignClientSystem feignClientSystem;

    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Autowired
    private ChecKTaskNumSeqMapper checKTaskNumSeqMapper;

    @Override
    public RecCheckForm saveUpdate(RecCheckForm recCheckForm) {
        int i = 1;
        HumanSession session = SessionHelper.get();
        // 获取当前登录部门领域
        List<SelectItem> itemList = feignClientSystem.loadUnitDomainsByUnitId(session.getUnitId());
        if (null == recCheckForm.getRecId() || 0 == recCheckForm.getRecId()) {
            HumanDetail detail = feignClientSystem.getHumanDetail(SessionHelper.get().getHumanId());
            recCheckForm.setTaskNum(this.calculate());
            recCheckForm.setCreateHumanId(session.getHumanId());
            recCheckForm.setCreateHuman(session.getHumanName());
            recCheckForm.setLawSubjectId(detail.getUnitId());
            recCheckForm.setLawSubject(detail.getUnitName());
            recCheckForm.setUnitCode(session.getUnitCode());
            Date date = new Date();
            recCheckForm.setCreateTime(date);
            recCheckMapper.insert(recCheckForm);
            List<RecCheckItem> list = recCheckForm.getRecCheckItems();
            if (list.size() > 0) {
                for (RecCheckItem item:list) {
                    item.setRecId(recCheckForm.getRecId());
                    item.setTaskNum(recCheckForm.getTaskNum());
                    item.setCheckItemId(i++);
                    recCheckItemMapper.insert(item);
                }
            }
        } else {
            // 查找当前要修改的内容
            RecCheck recCheck = recCheckMapper.selectByPrimaryKey(recCheckForm.getRecId());
            // 删除对应检查单检查事项
            recCheckItemMapper.deleteByRecId(recCheckForm.getRecId());
            recCheckForm.setCreateHumanId(recCheck.getCreateHumanId());
            recCheckForm.setCreateHuman(recCheck.getCreateHuman());
            recCheckForm.setLawSubjectId(recCheck.getLawSubjectId());
            recCheckForm.setLawSubject(recCheck.getLawSubject());
            recCheckForm.setCreateTime(recCheck.getCreateTime());
            recCheckForm.setTaskNum(recCheck.getTaskNum());
            recCheckForm.setUnitCode(session.getUnitCode());
            recCheckMapper.updateByPrimaryKey(recCheckForm);
            List<RecCheckItem> list = recCheckForm.getRecCheckItems();
            if (list.size() > 0) {
                for (RecCheckItem item:list) {
                    item.setRecId(recCheck.getRecId());
                    item.setTaskNum(recCheck.getTaskNum());
                    item.setCheckItemId(i++);
                    recCheckItemMapper.insert(item);
                }
            }
        }
        return recCheckForm;
    }

    @Override
    public PageInfo<RecCheckSearchBean> listUnitPage(RecCheckCriteriaBean criteria) {
        HumanSession session = SessionHelper.get();
        criteria.setUnitId(session.getUnitId());
        PageInfo<RecCheckSearchBean> page = PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize())
                .doSelectPageInfo(() -> {
                    recCheckMapper.listPage(criteria);
                });
        return page;
    }

    @Override
    public RecCheckForm getRecCheckByRecId(long recId) {
        RecCheck recCheck = recCheckMapper.selectByPrimaryKey(recId);
        RecCheckForm recCheckForm = new RecCheckForm();
        BeanUtils.copyProperties(recCheck, recCheckForm);
        String sql = "select * from rec_check_item where rec_id = " + recId + ";";
        List<RecCheckItem> item = jdbcTemplate.query(sql, new BeanPropertyRowMapper<RecCheckItem>(RecCheckItem.class));
        recCheckForm.setRecCheckItems(item);
       return recCheckForm;
    }

    @Override
    public void deleteCheeckById(long recId) {
        jdbcTemplate.update("update rec_check set delete_flag = ? where rec_id = ?",1,recId);
    }

    @Override
    public Map<String, Object> getLawDynamicsInfo(String unitCode) {
        String doMainSql = "SELECT count(*) AS `check` FROM rec_check where unit_code LIKE '"+unitCode+"%' ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(doMainSql);
        Map<String,Object> map = new HashMap<>();
        if (list!= null){
            list.forEach(map::putAll);
        }
        return map;
    }

    /**
     * 任务号：长度为17位，8位日期编码，2位业务编码，2位流程编码，5位序列号
     *
     * @param
     * @return
     */
    private synchronized String calculate() {
        Date now = new Date(); // 当前时间
        StringBuilder sb = new StringBuilder(DateHelper.dateToFormatStr(now, DateHelper.DATE_FORMAT_YMD));
        sb.append("01"); // 业务编码
        sb.append("01"); // 流程编码
        CheckTaskNumSeq seq = checKTaskNumSeqMapper.selectByPrimaryKey("01");
        int seqNum = 0;
        if (null != seq) {
            if (seq.getSeqDate().equals(DateHelper.getDateBegin(now))) {
                seqNum = seq.getSeqValue();
            }
            seq.setSeqValue(seqNum + 1);
            seq.setSeqDate(now);
            checKTaskNumSeqMapper.updateByPrimaryKey(seq);
        } else {
            seq = new CheckTaskNumSeq();
            seq.setSeqId("01");
            seq.setSeqDate(new Date());
            seq.setSeqValue(seqNum + 1);
            checKTaskNumSeqMapper.insert(seq);
        }
        sb.append(String.format("%05d", seq.getSeqValue()));
        return sb.toString();
    }
}
